import datetime
import logging

from django.core.paginator import Paginator, EmptyPage
from django.http import HttpResponseNotFound, JsonResponse, HttpResponseServerError
from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from django.views import View

from contents.utils import get_categories
from goods import constants
from goods.models import GoodsCategory, SKU, GoodsVisitCount
from goods.utils import get_breadcrumb
from meiduo_mall.utils.response_code import RETCODE

logger = logging.getLogger('django')

class DetailVisitView(View):
    """详情页分类商品访问量"""

    def post(self,request,category_id):
        """记录分类商品访问量"""
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return HttpResponseNotFound('缺少必要参数')

        # 获取今天的日期
        t = timezone.localtime()
        today_str = '%d-%02d-%02d' % (t.year,t.month,t.day)
        today_date = datetime.datetime.strptime(today_str,'%Y-%m-%d')
        try:
            # 查询今天的访问量
            counts_data = category.goodsvisitcount_set.get(date=today_date)
        except GoodsVisitCount.DoesNotExist:
            counts_data = GoodsVisitCount()
        try:
            counts_data.category = category
            counts_data.count += 1
            counts_data.save()
        except Exception as e:
            logger.error(e)
            return HttpResponseServerError('服务器异常')
        return JsonResponse({'code':RETCODE.OK,'error':'OK'})

class DetailView(View):
    """商品详情页"""

    def get(self,request,sku_id):
        """提供商品详情页"""

        # sku信息
        try:
            sku = SKU.objects.get(id = sku_id)
        except SKU.DoesNotExist:
            return render(request,'404.html')

        # 查询商品分类信息
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        # 评论
        comments = []
        order_goods = sku.ordergoods_set.all()
        for good in order_goods:
            comments.append({
                'username':good.order.user.username,
                'comment':good.comment,
                'score':good.score,

            })
        # 渲染页面
        context = {
            'categories':categories,
            'breadcrumb':breadcrumb,
            'sku':sku,
            'specs':goods_specs,
            "comments":comments
        }
        return render(request,'detail.html',context)


class HotGoodView(View):
    """商品热销排行"""

    def get(self,request,category_id):
        """提供热销商品排行json数据"""

        skus = SKU.objects.filter(category_id=category_id,is_launched=True).order_by('-sales')[:constants.HOT_LIMIT]
        # 序列化数据
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id':sku.id,
                'default_image':sku.default_image.url,
                'name':sku.name,
                'price':sku.price,
            })
        return JsonResponse({'code':RETCODE.OK,'errmsg':'OK','hot_skus':hot_skus})


class ListView(View):
    """商品列表页"""

    def get(self, request, category_id, page_num):
        """提供商品列表页"""
        # 判断category_id是否正确
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return HttpResponseNotFound('GoodsCategory does not exist')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(category)

        # 按照排序规则查询该分类商品SKU信息
        sort = request.GET.get('sort','default')
        if sort == 'price':
            # 按照价格由低到高
            sort_field = 'price'
        elif sort == 'hot':
            # 按照销量由高到低
            sort_field = '-sales'
        else:
            # 'price'和'sales'以外的所有排序方式都归为'default'
            sort = 'default'
            sort_field = 'create_time'
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(sort_field)
        #创建分页
        pagintor = Paginator(skus,constants.GOODS_LIST_LIMIT)
        try:
            page_skus = pagintor.page(page_num)
        except EmptyPage:
            return HttpResponseNotFound('Empty page')
        total_page = pagintor.num_pages

        # 渲染页面
        context = {
            'categories':categories,
            'breadcrumb':breadcrumb,
            'sort':sort,
            'category':category,
            'page_skus':page_skus,
            'total_page':total_page,
            'page_num':page_num,
        }
        return render(request, 'list.html', context)